<template>
  <div class="equipment-model-management">
    <!-- 顶部导航与新建按钮 -->
    <div class="header">
      <div class="title">设备物模型管理</div>
      <el-button type="primary" @click="openCreateDialog">+ 新建物模型</el-button>
    </div>

    <!-- 步骤指引 -->
    <el-steps :active="step" finish-status="success" class="steps">
      <el-step title="创建物模型" description="定义设备属性、服务和事件"></el-step>
      <el-step title="配置映射" description="关联设备实际参数"></el-step>
      <el-step title="发布模型" description="完成设备接入"></el-step>
    </el-steps>

    <!-- 主体内容 -->
    <div v-if="step === 0" class="model-list">
      <!-- 物模型列表 -->
      <el-table :data="modelList" style="width: 100%">
        <el-table-column prop="name" label="物模型名称" width="200"/>
        <el-table-column prop="createdAt" label="创建时间" width="180"/>
        <el-table-column prop="updatedAt" label="最后修改时间" width="180"/>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '已发布' ? 'success' : 'warning'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="editModel(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteModel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新建物模型弹窗 -->
    <el-dialog title="新建物模型" :visible.sync="createDialogVisible" width="400px">
      <el-radio-group v-model="createType">
        <el-radio label="graph">图形化建模</el-radio>
        <el-radio label="import">配置文件导入</el-radio>
      </el-radio-group>
      <div v-if="createType === 'import'" style="margin-top: 20px;">
        <el-upload
          action="#"
          :show-file-list="false"
          :before-upload="beforeUpload"
        >
          <el-button>选择配置文件</el-button>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="startCreate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图形化建模/数据点映射/发布流程 -->
    <div v-if="step > 0" class="model-workflow">
      <div v-if="step === 1" class="model-editor">
        <!-- 左侧组件库 -->
        <div class="component-lib">
          <div class="lib-title">组件库</div>
          <el-input placeholder="搜索组件" v-model="componentSearch" size="small" />
          <div class="lib-section">基础属性</div>
          <draggable
            :list="baseComponents"
            :options="{ group: { name: 'components', pull: 'clone', put: false }, sort: false }"
            :clone="cloneComponent"
            :move="() => false"
            class="lib-list"
          >
            <div
              v-for="element in baseComponents"
              :key="element.key"
              class="lib-item"
            >
              <i :class="element.icon"></i> {{ element.label }}
            </div>
          </draggable>
          <div class="lib-section">报警组件</div>
          <draggable
            :list="alarmComponents"
            :options="{ group: { name: 'components', pull: 'clone', put: false }, sort: false }"
            :clone="cloneComponent"
            :move="() => false"
            class="lib-list"
          >
            <div
              v-for="element in alarmComponents"
              :key="element.key"
              class="lib-item"
            >
              <i :class="element.icon"></i> {{ element.label }}
            </div>
          </draggable>
          <div class="lib-section">指令组件</div>
          <draggable
            :list="commandComponents"
            :options="{ group: { name: 'components', pull: 'clone', put: false }, sort: false }"
            :clone="cloneComponent"
            :move="() => false"
            class="lib-list"
          >
            <div
              v-for="element in commandComponents"
              :key="element.key"
              class="lib-item"
            >
              <i :class="element.icon"></i> {{ element.label }}
            </div>
          </draggable>
        </div>
        <!-- 中间画布 -->
        <div class="canvas-area">
          <draggable
            v-model="canvasComponents"
            :options="{ group: { name: 'components', pull: true, put: true } }"
            class="canvas"
            @end="onCanvasDrop"
          >
            <div
              v-for="(element, index) in canvasComponents"
              :key="element.key + index"
              class="canvas-item"
              :class="{ selected: selectedIndex === index }"
              @dblclick="editComponent(index)"
              @click="selectedIndex = index"
            >
              <i :class="element.icon"></i>
              <span>{{ element.label }}</span>
            </div>
            <div v-if="canvasComponents.length === 0" class="canvas-placeholder">
              <i class="el-icon-menu"></i>
              <div>将组件拖拽到此处进行建模</div>
            </div>
          </draggable>
        </div>
        <!-- 右侧属性编辑 -->
        <div class="property-editor">
          <div class="editor-title">模型配置</div>
          <el-form :model="modelForm" label-width="80px">
            <el-form-item label="模型名称">
              <el-input v-model="modelForm.name" placeholder="请输入模型名称" />
            </el-form-item>
            <el-form-item label="版本信息">
              <el-input v-model="modelForm.version" />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="modelForm.createdAt" type="datetime" disabled />
            </el-form-item>
          </el-form>
          <div class="editor-section">数据点配置</div>
          <div v-for="(comp, idx) in canvasComponents" :key="idx" class="data-point">
            <div class="data-point-title">
              {{ comp.label }}
              <el-tag size="mini" style="margin-left: 8px;">{{ comp.typeName }}</el-tag>
              <el-button type="text" size="mini" @click="editComponent(idx)">编辑</el-button>
              <el-button type="text" size="mini" @click="removeComponent(idx)">删除</el-button>
            </div>
            <div class="data-point-desc">标识符: {{ comp.key }}</div>
          </div>
          <div style="margin-top: 20px;">
            <el-button @click="saveDraft">保存草稿</el-button>
            <el-button type="primary" @click="nextStep">校验映射</el-button>
          </div>
        </div>
      </div>
      <!-- 数据点映射配置页 -->
      <div v-if="step === 2" class="mapping-page">
        <div class="mapping-title">数据点映射配置</div>
        <el-table :data="canvasComponents" style="width: 100%">
          <el-table-column prop="label" label="数据点名称" width="180"/>
          <el-table-column prop="typeName" label="类型" width="100"/>
          <el-table-column label="映射设备参数">
            <template slot-scope="scope">
              <el-input v-model="scope.row.mapping" placeholder="请输入设备参数/协议字段"/>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px;">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="validateMapping">校验映射</el-button>
        </div>
      </div>
      <!-- 发布模型页 -->
      <div v-if="step === 3" class="publish-page">
        <div class="publish-title">发布模型</div>
        <div class="publish-success">
          <i class="el-icon-success" style="font-size: 48px; color: #67c23a;"></i>
          <div style="font-size: 20px; margin: 16px 0 8px;">校验通过，模型已生成</div>
          <div style="color: #888;">可在模型列表查看并快速接入设备</div>
        </div>
        <div style="margin-top: 20px;">
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="publishModel">发布模型</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { Message } from 'element-ui'

export default {
  name: 'EquipmentModelManagement',
  components: { draggable },
  data() {
    return {
      step: 0, // 0:列表 1:建模 2:映射 3:发布
      createDialogVisible: false,
      createType: 'graph',
      modelList: [
        {
          name: '工业传感器设备',
          createdAt: '2024-01-15 14:30',
          updatedAt: '2024-01-20 09:15',
          status: '已发布'
        },
        {
          name: '智能温控设备',
          createdAt: '2024-01-16 10:20',
          updatedAt: '2024-01-19 16:45',
          status: '未发布'
        },
        {
          name: '环境监测设备',
          createdAt: '2024-01-17 15:50',
          updatedAt: '2024-01-18 11:30',
          status: '已发布'
        }
      ],
      // 组件库
      componentSearch: '',
      baseComponents: [
        { label: '设备型号', key: 'device_model', icon: 'el-icon-cpu', type: 'property', typeName: '属性' },
        { label: '设备状态', key: 'device_status', icon: 'el-icon-info', type: 'property', typeName: '属性' },
        { label: '运行状态', key: 'run_status', icon: 'el-icon-s-operation', type: 'property', typeName: '属性' }
      ],
      alarmComponents: [
        { label: '温度报警', key: 'temperature_alarm', icon: 'el-icon-warning', type: 'alarm', typeName: '报警' },
        { label: '速度报警', key: 'speed_alarm', icon: 'el-icon-refresh', type: 'alarm', typeName: '报警' }
      ],
      commandComponents: [
        { label: '启动指令', key: 'start_cmd', icon: 'el-icon-switch-button', type: 'command', typeName: '指令' },
        { label: '停止指令', key: 'stop_cmd', icon: 'el-icon-switch-button', type: 'command', typeName: '指令' }
      ],
      // 画布
      canvasComponents: [],
      selectedIndex: null,
      // 模型表单
      modelForm: {
        name: '',
        version: 'V1.0.0',
        createdAt: new Date()
      }
    }
  },
  methods: {
    openCreateDialog() {
      this.createDialogVisible = true
      this.createType = 'graph'
    },
    startCreate() {
      this.createDialogVisible = false
      if (this.createType === 'graph') {
        this.step = 1
        this.resetModel()
      } else {
        // 配置文件导入流程
        Message.success('配置文件导入功能待实现')
      }
    },
    beforeUpload(file) {
      // 这里可以实现配置文件解析
      Message.success('已选择文件: ' + file.name)
      return false
    },
    editModel(row) {
      // 编辑已存在模型（可扩展为实际数据回填）
      this.step = 1
      this.modelForm.name = row.name
      this.modelForm.version = 'V1.0.0'
      this.modelForm.createdAt = row.createdAt
      // 这里可加载row的canvasComponents
      this.canvasComponents = []
    },
    deleteModel(row) {
      this.modelList = this.modelList.filter(item => item !== row)
      Message.success('删除成功')
    },
    resetModel() {
      this.modelForm = {
        name: '',
        version: 'V1.0.0',
        createdAt: new Date()
      }
      this.canvasComponents = []
      this.selectedIndex = null
    },
    // 组件库拖拽克隆
    cloneComponent(component) {
      return { ...component }
    },
    // 画布拖拽
    onCanvasDrop() {
      // 组件拖拽到画布后自动弹出编辑
      if (this.selectedIndex === null && this.canvasComponents.length > 0) {
        this.selectedIndex = this.canvasComponents.length - 1
        this.editComponent(this.selectedIndex)
      }
    },
    editComponent(index) {
      const comp = this.canvasComponents[index]
      this.$prompt('编辑数据点名称', '编辑', {
        inputValue: comp.label,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.$set(this.canvasComponents, index, { ...comp, label: value })
      }).catch(() => {})
    },
    removeComponent(index) {
      this.canvasComponents.splice(index, 1)
      if (this.selectedIndex === index) this.selectedIndex = null
    },
    saveDraft() {
      Message.success('草稿已保存')
    },
    nextStep() {
      if (!this.modelForm.name) {
        Message.warning('请填写模型名称')
        return
      }
      if (this.canvasComponents.length === 0) {
        Message.warning('请拖拽并配置至少一个数据点')
        return
      }
      this.step = 2
    },
    prevStep() {
      this.step--
    },
    validateMapping() {
      // 简单校验
      const unMapped = this.canvasComponents.find(c => !c.mapping)
      if (unMapped) {
        Message.warning('请为所有数据点配置映射参数')
        return
      }
      this.step = 3
    },
    publishModel() {
      // 发布模型逻辑
      this.modelList.push({
        name: this.modelForm.name,
        createdAt: this.modelForm.createdAt,
        updatedAt: new Date().toISOString().slice(0, 16).replace('T', ' '),
        status: '已发布'
      })
      Message.success('模型发布成功')
      this.step = 0
    }
  }
}
</script>

<style scoped>
.equipment-model-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.title {
  font-size: 22px;
  font-weight: bold;
}
.steps {
  margin-bottom: 24px;
}
.model-list {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.model-workflow {
  display: flex;
  background: #fff;
  border-radius: 8px;
  min-height: 600px;
  padding: 0;
}
.model-editor {
  display: flex;
  width: 100%;
  min-height: 600px;
}
.component-lib {
  width: 220px;
  background: #f8f9fb;
  border-right: 1px solid #ebeef5;
  padding: 16px 8px;
}
.lib-title {
  font-weight: bold;
  margin-bottom: 8px;
}
.lib-section {
  margin: 16px 0 8px 0;
  font-size: 13px;
  color: #888;
}
.lib-list {
  min-height: 40px;
}
.lib-item {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 8px;
  cursor: grab;
  display: flex;
  align-items: center;
}
.lib-item i {
  margin-right: 8px;
}
.canvas-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 600px;
  background: #f5f7fa;
}
.canvas {
  width: 420px;
  min-height: 420px;
  background: #fff;
  border: 2px dashed #d3d3d3;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}
.canvas-placeholder {
  text-align: center;
  color: #888;
  margin-top: 120px;
}
.canvas-item {
  background: #f0f9eb;
  border: 1px solid #b7eb8f;
  border-radius: 4px;
  padding: 12px 20px;
  margin-bottom: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: border 0.2s;
}
.canvas-item.selected {
  border: 2px solid #409eff;
}
.canvas-item i {
  margin-right: 8px;
}
.property-editor {
  width: 320px;
  border-left: 1px solid #ebeef5;
  padding: 24px 16px;
  background: #fafbfc;
}
.editor-title {
  font-weight: bold;
  margin-bottom: 12px;
}
.editor-section {
  margin: 18px 0 8px 0;
  font-size: 13px;
  color: #888;
}
.data-point {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 10px;
}
.data-point-title {
  font-weight: bold;
  display: flex;
  align-items: center;
}
.data-point-desc {
  font-size: 12px;
  color: #888;
  margin-top: 2px;
}
.mapping-page, .publish-page {
  width: 100%;
  padding: 40px 80px;
}
.mapping-title, .publish-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 24px;
}
.publish-success {
  text-align: center;
  padding: 40px 0;
}
.publish-success .el-icon-success {
  margin-bottom: 16px;
}
</style>
